package com.gigi.service.manual;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gigi.common.Constants;
import com.gigi.entity.CourseEntity;
import com.gigi.entity.GigiClassEntity;
import com.gigi.enums.ErrorCodeEnum;
import com.gigi.enums.YesOrNoEnum;
import com.gigi.mapper.manual.CourseManualMapper;
import com.gigi.mapper.manual.JoinCourseManualMapper;
import com.gigi.model.*;
import com.gigi.service.generated.CourseService;
import com.gigi.service.generated.GigiClassService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CourseManageService {

    private final CourseService courseService;
    private final CourseManualMapper courseManualMapper;
    private final JoinCourseManualMapper joinCourseManualMapper;
    private final GigiClassService gigiClassService;

    public CourseManageService(CourseService courseService, CourseManualMapper courseManualMapper,
                               JoinCourseManualMapper joinCourseManualMapper, GigiClassService gigiClassService) {
        this.courseService = courseService;
        this.courseManualMapper = courseManualMapper;
        this.joinCourseManualMapper = joinCourseManualMapper;
        this.gigiClassService = gigiClassService;
    }

    /**
     * 保存接口
     *
     * @param request
     * @return
     */
    public Response save(CourseDO request) {
        // 新增
        if (ObjectUtil.isNull(request.getId())) {

            // 判断课程号是否唯一
            LambdaQueryWrapper<CourseEntity> wrapper = new LambdaQueryWrapper<CourseEntity>()
                    .eq(CourseEntity::getFlag, YesOrNoEnum.YES.getCode())
                    .eq(CourseEntity::getNo, request.getNo());
            if (courseService.count(wrapper) > 0) {
                return Response.buildFailure(ErrorCodeEnum.COURSE_NO_EXIST.getErrCode(), ErrorCodeEnum.COURSE_NO_EXIST.getErrDesc());
            }

            CourseEntity target = buildTarget(request);
            boolean isSuccess = courseService.save(target);
            if (!isSuccess) {
                return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
            }

            // 修改
        } else {

            CourseEntity oldModel = courseService.getById(request.getId());
            if (Objects.isNull(oldModel)) {
                return Response.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrDesc());
            }

            CourseEntity target = buildTarget(request);
            target.setId(oldModel.getId());
            boolean isSuccess = courseService.updateById(target);
            if (!isSuccess) {
                return Response.buildFailure(ErrorCodeEnum.EDIT_FAILED.getErrCode(), ErrorCodeEnum.EDIT_FAILED.getErrDesc());
            }
        }
        return Response.buildSuccess();
    }

    /**
     * 创建target对象公共方法
     *
     * @param request
     * @return
     */
    private CourseEntity buildTarget(CourseDO request) {
        CourseEntity target = new CourseEntity();
        target.setName(request.getName());
        target.setNo(request.getNo());
        target.setFlag(request.getFlag());
        target.setPic(StrUtil.isNotBlank(request.getPic()) ? request.getPic() : Constants.ORI_COURSE_PIC);
        target.setClassId(StrUtil.join(StrUtil.COMMA, request.getClassesId()));
        target.setUserId(request.getUserId());
        return target;
    }

    /**
     * 详情接口
     *
     * @param request
     * @return
     */
    public SingleResponse<CourseDO> detail(IdRequest request) {
        CourseEntity entity = courseService.getById(request.getId());
        if (Objects.isNull(entity)) {
            return SingleResponse.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrDesc());
        }
        CourseDO courseDO = new CourseDO();
        courseDO.setId(entity.getId());
        courseDO.setName(entity.getName());
        courseDO.setNo(entity.getNo());
        courseDO.setPic(entity.getPic());
        courseDO.setUserId(entity.getUserId());
        courseDO.setFlag(entity.getFlag());
        if (StrUtil.isNotBlank(entity.getClassId())) {
            courseDO.setClassesId(StrUtil.split(entity.getClassId(), StrUtil.COMMA));
        }
        return SingleResponse.of(courseDO);
    }

    /**
     * 更新有效性接口
     *
     * @param id
     * @return
     */
    public Response switchFlag(Long id) {
        CourseEntity oldModel = courseService.getById(id);
        if (Objects.isNull(oldModel)) {
            return Response.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrDesc());
        }
        CourseEntity entity = new CourseEntity();
        entity.setId(oldModel.getId());
        entity.setFlag(YesOrNoEnum.YES.getCode().equals(oldModel.getFlag()) ? YesOrNoEnum.NO.getCode() : YesOrNoEnum.YES.getCode());
        if (!courseService.updateById(entity)) {
            return Response.buildFailure(ErrorCodeEnum.EDIT_FAILED.getErrCode(), ErrorCodeEnum.EDIT_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 老师课程列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<CourseDO> listByTeacher(ListCourseRequest request) {
        if (request.getPageNum() < 1) {
            request.setPageNum(1);
        }
        if (request.getPageSize() < 1) {
            request.setPageSize(10);
        }
        int startIndex = (request.getPageNum() - 1) * request.getPageSize();
        List<CourseDO> courseDOS = courseManualMapper.listCourseForTeacher(request.getIfByPage(), request.getUserId(), request.getName(),
                request.getFlag(), startIndex,
                request.getPageSize());
        return MultiResponse.of(courseDOS, courseDOS.size());
    }

    /**
     * 学生课程列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<StudentCourseDO> listByStudent(ListCourseRequest request) {
        if (request.getPageNum() < 1) {
            request.setPageNum(1);
        }
        if (request.getPageSize() < 1) {
            request.setPageSize(10);
        }
        int startIndex = (request.getPageNum() - 1) * request.getPageSize();
        List<StudentCourseDO> studentCourseDOS = courseManualMapper.listCourseForStudent(request.getIfByPage(), request.getUserId(),
                request.getName(),
                request.getFlag(), startIndex,
                request.getPageSize());
        return MultiResponse.of(studentCourseDOS, studentCourseDOS.size());
    }

    /**
     * 搜索课程接口
     *
     * @param request
     * @return
     */
    public SingleResponse<CourseDO> search(SearchCourseRequest request) {
        CourseDO courseDO = courseManualMapper.searchCourse(request.getNo());
        return SingleResponse.of(courseDO);
    }

    /**
     * 计算课程总人数
     *
     * @param classesIdStr
     * @return
     */
    private int total(String classesIdStr) {
        LambdaQueryWrapper<GigiClassEntity> wrapper = new LambdaQueryWrapper<GigiClassEntity>()
                .in(GigiClassEntity::getId, StrUtil.split(classesIdStr, StrUtil.COMMA));
        return gigiClassService.list(wrapper).stream().map(GigiClassEntity::getCount).reduce(Integer::sum).orElse(0);
    }

    /**
     * 课程成员列表接口
     *
     * @param request
     * @return
     */
    public SingleResponse<CourseMemberDO> member(ListCourseMemberRequest request) {
        CourseMemberDO memberDO = new CourseMemberDO();
        memberDO.setTotal(total(request.getClassesIdStr()));
        memberDO.setJoinCourseDOS(joinCourseManualMapper.listCourseMember(request.getId()));
        return SingleResponse.of(memberDO);
    }

}
